package com.ekuaitu.kuaitu.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.LatLng;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.HeartBean;
import com.ekuaitu.kuaitu.bean.OperateBean;
import com.ekuaitu.kuaitu.bean.QueryLockBean;
import com.ekuaitu.kuaitu.ble.BluetoothHelper;
import com.ekuaitu.kuaitu.ble.ClientManager;
import com.ekuaitu.kuaitu.utils.BikeRepairDialog;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.NetUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RepairBTBikeActivity extends BaseActivity {
    @BindView(R.id.bikeLicense_bike_repair)
    TextView bikeLicenseBikeRepair;
    private String bikeLicense;
    private String bikeId;
    private String orderId;
    private int lockType;
    private Context mContext = this;
    private String mac;
    private ProgressDialog repairPorgress;
    private byte[] btToken = new byte[4];
    private byte[] loadPwd = new byte[6];
    private byte[] loadKey = new byte[16];
    private int caozuo = -1;
    private String model = android.os.Build.MODEL;
    private LatLng curPosition;

    @Override
    public int getLayoutId() {
        return R.layout.activity_repair_btbike;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        bikeLicenseBikeRepair.setText(bikeLicense);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        bikeLicense = intent.getStringExtra("bikeLicense");
        bikeId = intent.getStringExtra(IntentKey.INTENT_BIKE_ID);
        orderId = intent.getStringExtra(IntentKey.INTENT_ORDER_ID);
        lockType = intent.getIntExtra(IntentKey.INTENT_LOCK_TYPE, -1);
        if (lockType == 2 || lockType == 3 || lockType == 4) {
            mac = intent.getStringExtra("mac");
        }
        if (BikeInUseRedActivity.curPosition.longitude == 0 && BikeInUseRedActivity.curPosition.latitude == 0) {
            if (BikeInUseRedActivity.curPosition == null) {
                curPosition = MainActivity.curPosition;
            } else {
                curPosition = BikeInUseRedActivity.curPosition;
            }
        } else if (BikeInUseRedActivity.curPosition == null) {
            curPosition = MainActivity.curPosition;
        }
        if (curPosition == null) {
            curPosition = new LatLng(0, 0);
        }
    }


    @OnClick({R.id.return_bike_repair, R.id.hotLine_bike_repair, R.id.repair_bike_repair})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_bike_repair:
                finish();
                break;
            case R.id.hotLine_bike_repair:
                final KuaituDialog kuaituDialog2 = new KuaituDialog(mContext);
                kuaituDialog2.setTitle(getString(R.string.dialogTitle));
                kuaituDialog2.setMessage("是否拨打客服电话" + MyApplication.getInstance().getHotLine());
                kuaituDialog2.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                        startActivity(intent);
                        kuaituDialog2.dismiss();
                    }
                });
                kuaituDialog2.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog2.dismiss();
                    }
                });
                kuaituDialog2.show();
                break;
            case R.id.repair_bike_repair:
                if (lockType == 1) {
                    repairPorgress = new ProgressDialog(RepairBTBikeActivity.this);
                    repairPorgress.setMessage("正在修复中，请耐心等待...");
                    repairPorgress.setCancelable(false);
                    repairPorgress.show();
                    sendRepairResult("0", "1", "1");
                    repairGpsBikeFirst("open");


                } else if (lockType == 2 || lockType == 3 || lockType == 4) {
                    repairPorgress = new ProgressDialog(RepairBTBikeActivity.this);
                    repairPorgress.setMessage("正在修复中，请耐心等待...");
                    repairPorgress.setCancelable(false);
                    repairPorgress.show();
                    caozuo = 0;
                    //第一次 开始
                    sendRepairResult("0", "1", "2");
                    requestBTBikeInfo(bikeId);
                }
                break;
        }
    }

    private void repairGpsBikeFirst(String cmd) {
        commitBikeLogPre(FIRST);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).repairGpsBike(MyApplication.getInstance().getRequestFieldMap(),orderId, bikeId, "1", cmd, curPosition.latitude + "",
                curPosition.longitude + "").enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        repairPorgress.dismiss();
                        final BikeRepairDialog selfDialog = new BikeRepairDialog(mContext);
                        selfDialog.setTitle("");
                        selfDialog.setMessage("已向车锁发出修复指令，请尝试手动关闭车锁。");
                        selfDialog.setYesOnclickListener("失败，重新修复", new BikeRepairDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                commitBikeLogFailed(FIRST, 0, "失败，重新修复");
                                //第一次 失败
                                sendRepairResult("2", "1", "1");
                                //第二次 开始
                                sendRepairResult("0", "2", "1");
                                //发送复位指令
                                repairGpsBikeSecond("close");
                                selfDialog.dismiss();
                                repairPorgress = new ProgressDialog(RepairBTBikeActivity.this);
                                repairPorgress.setMessage("正在修复中，请耐心等待...");
                                repairPorgress.setCancelable(false);
                                repairPorgress.show();
                            }
                        });
                        selfDialog.setNoOnclickListener("关锁成功", new BikeRepairDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                commitBikeLogSuccess(FIRST);
                                selfDialog.dismiss();
                                sendRepairResult("1", "1", "1");
                                finish();
                            }
                        });
                        selfDialog.show();
                        selfDialog.setCancelable(false);
                        selfDialog.setButtonImageShow(false);


                    } else {
                        repairPorgress.dismiss();
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                repairPorgress.dismiss();
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void repairGpsBikeSecond(String cmd) {
        commitBikeLogPre(SECOND);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).repairGpsBike(MyApplication.getInstance().getRequestFieldMap(),orderId, bikeId, "1", cmd,
                curPosition.latitude + "", curPosition.longitude + ""
        ).enqueue(new Callback<OperateBean>() {
            @Override
            public void onResponse(Call<OperateBean> call, Response<OperateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        repairPorgress.dismiss();
                        final BikeRepairDialog selfDialog = new BikeRepairDialog(mContext);
                        selfDialog.setTitle("");
                        selfDialog.setMessage("操作完成，请手动关闭车锁。");
                        selfDialog.setYesOnclickListener("  联系客服", new BikeRepairDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                commitBikeLogFailed(SECOND, 0, "失败联系客服");
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_DIAL);
                                intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                                startActivity(intent);
                                selfDialog.dismiss();
                                //第二次 失败
                                sendRepairResult("2", "2", "1");
                            }
                        });
                        selfDialog.setNoOnclickListener("关锁成功", new BikeRepairDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                commitBikeLogSuccess(SECOND);
                                selfDialog.dismiss();
                                //第二次  成功
                                sendRepairResult("1", "2", "1");
                                finish();
                            }
                        });
                        selfDialog.show();
                        selfDialog.setCancelable(false);
                        selfDialog.setButtonImageShow(true);

                    } else {
                        repairPorgress.dismiss();
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<OperateBean> call, Throwable t) {
                repairPorgress.dismiss();
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }


    private void sendRepairResult(String action_type, String order_type, String lock_type) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL_PHP).sendRepairResult(MyApplication.getInstance().getRequestFieldMap(),action_type, order_type, lock_type, model, orderId, bikeLicense, "android", MyApplication.getInstance().getAppVersion()).enqueue(new Callback<HeartBean>() {
            @Override
            public void onResponse(Call<HeartBean> call, Response<HeartBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrorCode() == 0) {
                        Log.i("repair", "repair");
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMsg(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<HeartBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }


    //蓝牙打开结果
    private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            if (openOrClosed) {
                BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
            } else {
                repairPorgress.dismiss();
                ToastCompat.makeText(mContext, "蓝牙未开启", Toast.LENGTH_LONG).show();
            }
        }
    };

    //蓝牙设备搜索结果
    private final SearchResponse mSearchResponse = new SearchResponse() {
        @Override
        public void onSearchStarted() {

        }

        @Override
        public void onDeviceFounded(SearchResult device) {
            if (device.scanRecord[5] == 0x01 && device.scanRecord[6] == 0x02) {
                if (device.getAddress().equals(mac)) {
                    ClientManager.getClient().stopSearch();
                    BluetoothHelper.getInstance().connectDevice(mac, loadPwd, loadKey, new BluetoothHelper.OnConnectListener() {
                        @Override
                        public void onConnectSuccess() {
                            BluetoothHelper.getInstance().openLock();
                        }

                        @Override
                        public void onConnectFailed() {
                            repairPorgress.dismiss();
                            final KuaituDialog kuaituDialog = new KuaituDialog(mContext);
                            kuaituDialog.setTitle(getString(R.string.dialogTitle));
                            kuaituDialog.setMessage("对不起！未能连接到这个单车，您可以再次尝试");
                            kuaituDialog.setYesOnclickListener("确认", new KuaituDialog.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    kuaituDialog.dismiss();
                                    ClientManager.getClient().closeBluetooth();
                                }
                            });
                            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    kuaituDialog.dismiss();
                                    ClientManager.getClient().closeBluetooth();
                                }
                            });
                            kuaituDialog.show();
                        }
                    });
                }
            }
        }

        @Override
        public void onSearchStopped() {
            //未搜索到
            final KuaituDialog kuaituDialog = new KuaituDialog(RepairBTBikeActivity.this);
            kuaituDialog.setTitle(getString(R.string.dialogTitle));
            kuaituDialog.setMessage("未扫描到该单车，请将手机靠近车锁再试");
            kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    kuaituDialog.dismiss();
                }
            });
            kuaituDialog.setCancelable(false);
            kuaituDialog.show();
        }

        @Override
        public void onSearchCanceled() {
            //搜索到后执行此方法，此时已经发起连接

        }
    };

    private void requestBTBikeInfo(String bikeId) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).requestBTBikeInfo(MyApplication.getInstance().getRequestFieldMap(),bikeId, "0")
                .enqueue(new Callback<QueryLockBean>() {
                    @Override
                    public void onResponse(Call<QueryLockBean> call, final Response<QueryLockBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                mac = response.body().getAttachment().getBikeMachineUnique();
                                String key = response.body().getAttachment().getBikeMachineKey();
                                String pwd = response.body().getAttachment().getBikeMachinePassword();
                                String[] KEY = key.split(",");
                                String[] PWD = pwd.split(",");
                                for (int i = 0; i < 16; i++) {
                                    loadKey[i] = Byte.parseByte(KEY[i]);
                                }
                                for (int j = 0; j < 6; j++) {
                                    loadPwd[j] = Byte.parseByte(PWD[j]);
                                }
                                if (ClientManager.getClient().isBluetoothOpened()) {
                                    int status = ClientManager.getClient().getConnectStatus(mac);
                                    Log.i("scanresult", "firstscan" + status + "");
                                    if (status == 2) {
                                        btToken = MyApplication.btToken;
                                        BluetoothHelper.getInstance().setBluetoothCommandCallback(commandCallback);//蓝牙指令回调
                                        BluetoothHelper.getInstance().openLock();
                                    } else {
                                        BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                                    }

                                } else {
                                    ClientManager.getClient().registerBluetoothStateListener(mBluetoothStateListener);
                                    ClientManager.getClient().openBluetooth();
                                }
                            } else {
                                repairPorgress.dismiss();
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                            }
                        } else {
                            repairPorgress.dismiss();
                            ToastCompat.makeText(mContext,getResources().getString(R.string.serverError), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<QueryLockBean> call, Throwable t) {
                        repairPorgress.dismiss();
                        ToastCompat.makeText(mContext,getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).setGravity(Gravity.CENTER, 0, 0).show();
                    }
                });

    }


    private static final int FIRST = 0;
    private static final int SECOND = 1;

    //bike-APP端操作日志记录 操作前
    private void commitBikeLogPre(int action) {
        switch (action) {
            case FIRST:
                NetUtils.commitBikeLog(RepairBTBikeActivity.this, BikeInUseRedActivity.aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "3", "1", "0", "", "");
                break;
            case SECOND:
                NetUtils.commitBikeLog(RepairBTBikeActivity.this, BikeInUseRedActivity.aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "4", "1", "0", "", "");
                break;
        }

    }

    //bike-APP端操作日志记录 操作成功
    private void commitBikeLogSuccess(int action) {
        switch (action) {
            case FIRST:
                NetUtils.commitBikeLog(RepairBTBikeActivity.this, BikeInUseRedActivity.aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "3", "2", "0", "200", "");
                break;
            case SECOND:
                NetUtils.commitBikeLog(RepairBTBikeActivity.this, BikeInUseRedActivity.aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "4", "2", "0", "200", "");
                break;
        }
    }

    //bike-APP端操作日志记录 操失败
    private void commitBikeLogFailed(int action, int errorcode, String errormsg) {
        switch (action) {
            case FIRST:
                NetUtils.commitBikeLog(RepairBTBikeActivity.this, BikeInUseRedActivity.aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "3", "3", "1", errorcode + "", errormsg);
                break;
            case SECOND:
                NetUtils.commitBikeLog(RepairBTBikeActivity.this, BikeInUseRedActivity.aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "4", "3", "1", errorcode + "", errormsg);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    /**
     * 蓝牙指令响应回调
     */
    private BluetoothHelper.BluetoothCommandCallback commandCallback = new BluetoothHelper.BluetoothCommandCallback() {

        @Override
        public void onSetReturnMode(boolean isSuccessful) {

        }

        @Override
        public void onGetToken(byte[] btToken) {
            MyApplication.btToken = btToken;
            if (caozuo == 0) {
                BluetoothHelper.getInstance().openLock();
            }
        }

        @Override
        public void onOpenLock(boolean isSuccessful) {
            //开锁成功或者失败均执行 第一次修复
            repairPorgress.dismiss();
            final BikeRepairDialog selfDialog = new BikeRepairDialog(mContext);
            selfDialog.setTitle("");
            selfDialog.setMessage("已向车锁发出修复指令，请尝试手动关闭车锁。");
            selfDialog.setYesOnclickListener("失败，重新修复", new BikeRepairDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    //第一次 失败
                    sendRepairResult("2", "1", "2");
                    //第二次 开始
                    sendRepairResult("0", "2", "2");
                    //发送复位指令
                    caozuo = 1;
                    BluetoothHelper.getInstance().resetLock();
                    selfDialog.dismiss();
                    repairPorgress = new ProgressDialog(RepairBTBikeActivity.this);
                    repairPorgress.setMessage("正在修复中，请耐心等待...");
                    repairPorgress.setCancelable(false);
                    repairPorgress.show();
                }
            });
            selfDialog.setNoOnclickListener("关锁成功", new BikeRepairDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    selfDialog.dismiss();
                    sendRepairResult("1", "1", "2");
                    finish();
                }
            });
            selfDialog.show();
            selfDialog.setCancelable(false);
            selfDialog.setButtonImageShow(false);
        }

        @Override
        public void onCloseLock(boolean isSuccessful) {

        }

        @Override
        public void onResetLock(boolean isSuccessful) {
            //复位成功或者失败均执行  第二次修复
            repairPorgress.dismiss();
            final BikeRepairDialog selfDialog = new BikeRepairDialog(mContext);
            selfDialog.setTitle("");
            selfDialog.setMessage("操作完成，请手动关闭车锁。");
            selfDialog.setYesOnclickListener("  联系客服", new BikeRepairDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                    startActivity(intent);
                    selfDialog.dismiss();
                    //第二次 失败
                    sendRepairResult("2", "2", "2");
                }
            });
            selfDialog.setNoOnclickListener("关锁成功", new BikeRepairDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    selfDialog.dismiss();
                    //第二次  成功
                    sendRepairResult("1", "2", "2");
                    finish();
                }
            });
            selfDialog.show();
            selfDialog.setCancelable(false);
            selfDialog.setButtonImageShow(true);
        }

        @Override
        public void onGetLockPower(byte power) {

        }

        @Override
        public void onCheckLockStatus(boolean isOpen) {

        }
    };
}
